using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Move3Boll1 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        // this.gameObject
    }

    public List<GameObject> celestialBodies;
    public Vector3 StartForce;
    //public 
        float G=9.8f;//引力常量
    void Awake(){
        SearchBodies();
        // gameObject.GetComponent<Rigidbody>().AddForce(StartForce);
        //初始速度
        if(gameObject.name=="Sun")
            return;

        var target = GameObject.Find("Sun");
        float distance = Vector3.Distance(target.transform.position, gameObject.transform.position);

        var blastmovespeed =(float) Math.Sqrt( G * target.GetComponent<Rigidbody>().mass/ distance);
        Vector3 sudu =new Vector3 (blastmovespeed,0 ,0);
        //gameObject.GetComponent<Rigidbody>().velocity =sudu ;
    }
    private void FixedUpdate() {
        // Console.WriteLine("FixedUpdate");
        for (int i = 0; i < celestialBodies.Count; i++){
            if (celestialBodies[i] != null)
            {
                Running(celestialBodies[1]);
            }

        }
    }
    public void Running(GameObject target)
    {

        //万有引力定律: F=G"m1"m2/r~2
        Vector3 dir=(target.transform.position-transform.position).normalized;
        float distance =Vector3.Distance(target.transform.position,gameObject.transform.position);
        float m1=target.GetComponent<Rigidbody>().mass;
        float m2=gameObject.GetComponent<Rigidbody>().mass;
        gameObject.GetComponent<Rigidbody>().AddForce((dir*m1*m2)/(distance*distance));
    }
    public void SearchBodies(){


        //重新查找场景内天体个数
        celestialBodies=new List<GameObject>();
        GameObject[] Bodies=GameObject.FindGameObjectsWithTag("celestialBodies");
            for (int i = 0; i <Bodies.Length; i++){
            //if (gameObject.transform.position!=Bodies[i].transform.position)
            if (gameObject!= Bodies[i])
                if (Bodies[i]!=null)
                        celestialBodies.Add(Bodies[i]);
            }
        
    }
}
